
// 禁止转载 禁止转载

"ui";
var version = "1.2.1"
var count_num = 0;
var content = "";
var time_his = 0;
var thread = "";
var set_time_global = 0;
var daojishi_his = "";
var d = [];
var content = [];
var color = "#009688";
var ColoredButton = (function () {
    //继承ui.Widget
    util.extend(ColoredButton, ui.Widget);

    function ColoredButton() {
        //调用父类构造函数
        ui.Widget.call(this);
        //自定义属性color，定义按钮颜色
        this.defineAttr("color", (view, name, defaultGetter) => {
            return this._color;
        }, (view, name, value, defaultSetter) => {
            this._color = value;
            view.attr("backgroundTint", value);
        });
        //自定义属性onClick，定义被点击时执行的代码
        this.defineAttr("onClick", (view, name, defaultGetter) => {
            return this._onClick;
        }, (view, name, value, defaultSetter) => {
            this._onClick = value;
        });
    }
    ColoredButton.prototype.render = function () {
        return (
            <button textSize="16sp" style="Widget.AppCompat.Button.Colored" w="auto" />
        );
    }
    ColoredButton.prototype.onViewCreated = function (view) {
        view.on("click", () => {
            if (this._onClick) {
                eval(this._onClick);
            }
        });
    }
    ui.registerWidget("colored-button", ColoredButton);
    return ColoredButton;
})();
// 提醒参数设置
var storage = storages.create("mention_software");
var zd = storage.get("mention_type_zd")
var sy = storage.get("mention_type_sy")
if (zd == null || sy == null){
    zd = 1;
    sy = 0;
    storage.put("mention_type_zd", 1);
    storage.put("mention_type_sy", 0);
}


// 禁止转载 禁止转载

// 提醒模式函数
// 提示函数
function 铃声通知(播放时长, 音量) {
    var 音量 = 音量 || 6
    var 播放时长 = 播放时长 || 1000
    var 铃声 = android.media.RingtoneManager.TYPE_NOTIFICATION
    var mp = new android.media.MediaPlayer();
    device.setMusicVolume(音量)
    mp.setDataSource(context, android.media.RingtoneManager.getDefaultUri(铃声));
    mp.prepare(); mp.start();
}

function 震动(vibrate_time) {
    var vibrate_time = vibrate_time || 500
    device.vibrate(vibrate_time);
}

function mention() {
    if (zd == 1) {
        if (sy == 0) {
            震动();
        } else {
            铃声通知(6, 500)
        }
    } else {
        if (sy == 0) {
            pass;
        } else {
            铃声通知(6, 500);
        }
    }
}

// ------------------------------------
function shanchu() {
    count_num = 0;
    time_his = 0;
    content = [];
    ui.jia_l.setText(count_num + "");
    ui.ShowResult.setText("")
}
// 禁止转载 禁止转载
function hisCon() {
    var today1 = new Date();
    var h1 = today1.getHours();
    var m1 = today1.getMinutes();
    var s1 = today1.getSeconds();
    var time_now = today1.getTime()
    if (time_his == 0) { var time_delta = 0 } else { td = (time_now - time_his) / 1000; time_delta = td.toFixed(2) }
    content.push({ "时间": h1 + ":" + m1 + ":" + s1, "间隔": time_delta, "计数": count_num })
    time_his = time_now
    cj = JSON.stringify(content).replace(/\},/g, "},\n")
    return cj;
}
// 禁止转载 禁止转载
function show_result() {
    text_font_size();
    var settime = ui.daojishi.getText();
    if (settime != "") {
        ui.state.setText("")
        set_time_global = settime
        ui.daojishi.setText("");
        thread = threads.start(function () {
            while (true) {
                for (var i = set_time_global; i >= 0; i--) {
                    ui.daojishi_show.setText(i + "");
                    sleep(1000);
                }
                threads.start(function () {
                    try { HisJishiCon(d) } catch (e) { toast("Hello") }
                    for (var j = 0; j <= 1; j++) {
                        // device.vibrate(1000);
                        mention()
                        sleep(500);
                    }
                })
            }
        })
    } else (toast("请设定时间后再开始"))
}
// 禁止转载 禁止转载
function cancel_jishi() {
    ui.daojishi_show.setText("0");
    set_time_global = 0;
    threads.shutDownAll();
    ui.state.setText("")
    ui.ShowDaojishiResult.setText("")
    ui.his_time_count.setText("0")
    d = []
}
// 禁止转载 禁止转载
function HisJishiCon(dd) {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    var n = dd.length + 1;
    ui.his_time_count.setText(n + "")
    dd.push({ "time": h + ":" + m + ":" + s, "n": n + "次" });
    ui.ShowDaojishiResult.setText(JSON.stringify(dd));
}
// 禁止转载 禁止转载
function text_font_size() {
    var numT = ui.daojishi.getText()
    var setTextSize1 = 200;
    if (numT != "") {
        var num = parseInt(numT);
        if (num <= 999) {
            setTextSize1 = 200;
        } else if (num > 999 && num < 9999) {
            setTextSize1 = 150;
        } else {
            setTextSize1 = 100;
        }
    } else { setTextSize1 = 200; }
    ui.daojishi_show.setTextSize(setTextSize1);
}
// 禁止转载 禁止转载

ui.layout(
    <drawer id="drawer">
        <vertical>
            <appbar>
                <toolbar id="toolbar" title="Mention Countor" />
                <tabs id="tabs" />
            </appbar>
            <viewpager id="viewpager">
                <frame>
                    <vertical>
                        <horizontal>
                            <input id="daojishi" hint="输入倒计时间隔(秒)" textColor="black" textSize="16sp" marginTop="16" w="200" />
                            <colored-button id="start" text="开始执行" color="#3399ff" marginTop="13" onClick="show_result()" />
                            <colored-button id="finish" text="终止执行" color="#F5658E" marginTop="13" onClick="cancel_jishi()" />
                        </horizontal>
                        <button id='daojishi_show' text="0" textSize="200sp" style="Widget.AppCompat.Button.Colored" w='*' />
                        <text id="state" textSize="15sp" textColor="red" marginLeft="10" />
                        <horizontal>
                            <text text="提醒次数: " textSize="20sp" textColor="black" marginLeft="10" gravity="right" w="180" />
                            <text id="his_time_count" text="0" textSize="50sp" textColor="black" textStyle="bold" padding="0" w="*" gravity="left" marginLeft="20" />
                        </horizontal>
                        <text text="History Record (每轮停止时间 || 已循环次数 )" textColor="black" textSize="16sp" marginTop="5" marginLeft="10" />
                        <input id="ShowDaojishiResult" textSize="16sp" marginLeft="10" lines="10" />
                    </vertical>
                </frame>
                <frame>
                    <vertical>
                        <colored-button text="删除" color="#ff5722" onClick="shanchu()" />
                        <button id='jia' text="+" textSize="50sp" style="Widget.AppCompat.Button.Colored" w="*" h="auto" />
                        <button id='jia_l' text="0" textSize="200sp" style="Widget.AppCompat.Button.Borderless" w='*' />
                        <button id='jian' text="-" textSize="50sp" style="Widget.AppCompat.Button.Colored" w="*" h="auto" />
                        <text text="History Record (操作时间 || 时间间隔s || 计数记录)" textColor="black" textSize="16sp" marginTop="5" marginLeft="10" />
                        <input id="ShowResult" textSize="16sp" marginLeft="10" lines="5" />
                    </vertical>
                </frame>
            </viewpager>
        </vertical>
        <vertical layout_gravity="left" bg="#ffffff" w="280">
            <img w="280" h="200" scaleType="fitXY" src="http://images.shejidaren.com/wp-content/uploads/2014/10/023746fki.jpg" />
            <list id="menu">
                <horizontal bg="?selectableItemBackground" w="*">
                    <img w="50" h="50" padding="16" src="{{this.icon}}" tint="{{color}}" />
                    <text textColor="black" textSize="15sp" text="{{this.title}}" layout_gravity="center" />
                </horizontal>
            </list>
        </vertical>
    </drawer>
);

// 禁止转载 禁止转载

ui.daojishi_show.on("click", () => {
    if (thread != "") {
        if (thread.isAlive()) { //正在执行中
            threads.shutDownAll();
            ui.state.setText("已暂停")
        } else { // 已终止
            var settime = ui.daojishi_show.getText();
            ui.state.setText("")
            if (settime > 0) {
                thread = threads.start(function () {
                    for (var i = settime; i >= 0; i--) {
                        ui.daojishi_show.setText(i + "");
                        sleep(1000);
                    }
                    threads.start(function () {
                        // toast('本轮计时结束');
                        try { HisJishiCon(d) } catch (e) { toast("Hello") }
                        for (var j = 0; j <= 1; j++) {
                            //device.vibrate(1000);
                            mention()
                            sleep(500);
                        }
                    })
                    while (true) {
                        for (var i = set_time_global; i >= 0; i--) {
                            ui.daojishi_show.setText(i + "");
                            sleep(1000);
                        }
                        threads.start(function () {
                            try { HisJishiCon(d) } catch (e) { toast("Hello") }
                            for (var j = 0; j <= 1; j++) {
                                //device.vibrate(1000);
                                mention()
                                sleep(500);
                            }
                        })
                    }
                })
            }
        }
    }
})
// 禁止转载 禁止转载
ui.jia.on("click", () => {
    count_num = count_num + 1;
    ui.jia_l.setText(count_num + "")
    ui.ShowResult.setText(hisCon())
});
// 禁止转载 禁止转载
ui.jia_l.on("click", () => {
    // toast("+1");
    count_num = count_num + 1;
    ui.jia_l.setText(count_num + "")
    ui.ShowResult.setText(hisCon())
});
// 禁止转载 禁止转载
ui.jian.on("click", () => {
    // if (count_num >1){count_num = count_num-1;
    // }
    // else{count_num=0;}
    count_num = count_num - 1;
    ui.jia_l.setText(count_num + "")
    ui.ShowResult.setText(hisCon())
});

//创建选项菜单(右上角)
ui.emitter.on("create_options_menu", menu => {
    menu.add("设置");
    menu.add("关于");
});
//监听选项菜单点击
ui.emitter.on("options_item_selected", (e, item) => {
    switch (item.getTitle()) {
        case "设置":
            showSetting();
            break;
        case "关于":
            http.get("https://gitee.com/barlown/mention/raw/master/Mention%20%E6%BA%90%E7%A0%81/version_check.txt", {}, function (res, err) {
                if (err) {
                    alert("错误", err);
                    return;
                }
                alert("关于", "Mention当前版本为 v" + version + " \n最新版本为 v" + res.body.string());
            });
            break;
    }
    e.consumed = true;
});
activity.setSupportActionBar(ui.toolbar);

// 添加设置，右上角的设置
function showSetting() {
    var items = ["震动", "响铃"];
    var selectedIndex = 0; // 初始选择
    try {
        if (zd == 1) {
            selectedIndex = 0;
        } else {
            selectedIndex = 1;
        }
    } catch (e) { selectedIndex = 0; }
    dialogs.singleChoice("提示模式设置", items, selectedIndex, function (index) {
        if (index === 0) { // 选择了"震动"
            zd = 1;
            sy = 0;
            storage.put("mention_type_zd", 1);
            storage.put("mention_type_sy", 0);
            toast("提示模式设置为： 震动");
        } else if (index === 1) { // 选择了"响铃"
            zd = 0;
            sy = 1;
            storage.put("mention_type_zd", 0);
            storage.put("mention_type_sy", 1);
            toast("提示模式设置为： 响铃");
        }
    });
}

// 数据导出部分----------
// #1 数据格式处理函数
function format_txt(rawdata) {
    if (rawdata != "") {
        rawdata = rawdata.replace('\n', '')
        var data = JSON.parse(rawdata)
        var keysname = ''
        if (data.length >= 1) {
            keysname = Object.keys(data[0])
        }
        // txt文件格式整理
        // 第一行表头
        var title = ''
        for (let i in keysname) {
            title = title + keysname[i] + '\t\t\t'
        }
        var table_title = title + '\n'
        // 文字内容
        var content = '';
        print(keysname)
        for (let j in data) {
            for (let i in keysname) {
                content = content + (data[j][keysname[i]]).toString() + '\t\t\t'
            }
            content = content + '\n'
        }
        const format_data = table_title + content
        return format_data
    }
    else { return rawdata }
}
// #2 数据导出函数
function export_data() {
    var savedata = ''
    var items = ["导出提醒数据", "导出计数数据"];
    var selectedIndex = 0; // 初始选择
    dialogs.singleChoice("数据导出设置", items, selectedIndex, function (index) {
        if (index === 0) { // 选择了"提醒数据导出"
            savedata = ui.ShowDaojishiResult.text();
        } else if (index === 1) { // 选择了"计数数据导出"
            savedata = ui.ShowResult.text();
        } else { index = null }
        // 文件写入
        files.ensureDir("/sdcard/Download/Mention/");
        if (index != null) {
            filename = items[index] +"_"+ (new java.text.SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date())).toString() + ".txt"
            path = "/sdcard/Download/Mention/" + filename
            try {
                格式化的数据 = format_txt(savedata)
                files.write(path, 格式化的数据);
                toast("文件写入成功，保存于" + path);
            } catch (e) { toast("文件写入失败\n" + e) }
        }
    });
}

//设置滑动页面的标题
ui.viewpager.setTitles(["计时器", "计数器"]);
//让滑动页面和标签栏联动
ui.tabs.setupWithViewPager(ui.viewpager);

//让工具栏左上角可以打开侧拉菜单
ui.toolbar.setupWithDrawer(ui.drawer);

ui.menu.setDataSource([
    {
        title: "导出记录数据",
        icon: "@drawable/ic_edit_black_48dp"
    },
    {
        title: "访问软件官网&帮助",
        icon: "@drawable/ic_favorite_black_48dp"
    },
    {
        title: "软件仓库 密码c7gw",
        icon: "@drawable/ic_movie_black_48dp"
    },
    {
        title: "退出",
        icon: "@drawable/ic_exit_to_app_black_48dp"
    }
]);

ui.menu.on("item_click", item => {
    switch (item.title) {
        case "导出记录数据":
            export_data();
            break;
        case "访问软件官网&帮助":
            var Intent = android.content.Intent;
            var Uri = android.net.Uri;
            var intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://gitee.com/barlown/mention/"));
            activity.startActivity(intent);
            break;
        case "软件仓库 密码c7gw":
            var Intent = android.content.Intent;
            var Uri = android.net.Uri;
            var intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://wwak.lanzouy.com/b02976rre"));
            activity.startActivity(intent);
            break;
        case "退出":
            ui.finish();
            break;
    }
})